import http from "@ohos.net.http";
import dataModule from "../model/dataMdule";

class HttpRequest {
  baseUrl: string = ""
  param: object = {}

  getData(): Promise<dataModule> {
    return new Promise<dataModule>((resolve, reject) => {
      let httpRequest = http.createHttp()
      httpRequest.request(this.baseUrl, { method: http.RequestMethod.GET }).then(res => {
        if (res.responseCode === 200) {
          resolve(JSON.parse(res.result.toString()))
        } else {
          reject("数据返回失败")
        }
      }).catch(error => {
        reject("网络访问失败")
      });

    })
  }

  postData(): Promise<dataModule> {
    return new Promise<dataModule>((resolve, reject) => {
      let httpRequest = http.createHttp()
      let param = this.param
      httpRequest.request(this.baseUrl, { method: http.RequestMethod.POST, extraData: param }).then(res => {
        if (res.responseCode === 200) {
          resolve(JSON.parse(res.result.toString()))
        } else {
          reject("数据返回失败")

        }
      }).catch(error => {
        reject("网络访问失败")
      });
    })
  }
}

const httpRequest = new HttpRequest()

export default httpRequest as HttpRequest;